package com.app.twth.ui.adjust.lpn;


import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.app.twth.BR;
import com.app.twth.R;
import com.app.twth.app.AppRouter;
import com.app.twth.app.Constant;
import com.app.twth.base.BaseActivity;
import com.app.twth.databinding.ActivityAdjustSkuBinding;
import com.app.twth.ui.adjust.AdjustViewModel;
import com.app.twth.ui.adjust.retally.ReTally;
import com.app.twth.ui.tally.lpn.TalliedSku;
import com.app.twth.ui.tally.lpn.TallyLPNAdapter;
import com.app.twth.utils.ToastUtil;
import com.app.twth.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * @describe :
 */
public class AdjustSkuActivity extends BaseActivity<ActivityAdjustSkuBinding, AdjustViewModel> {
    private String TAG = getClass().getSimpleName();
    private ReTally tally;
    private int type = 0;

    private TallyLPNAdapter adapter;
    private List<String> barcodes = new ArrayList<>();

    @Override
    protected void initListener() {
        viewModel.LpnSkuLiveData.observe(this, data -> {
            tally = data;
            List<TalliedSku> skuList = tally.getSkuList();
            if (skuList == null || skuList.size() == 0) {
                Intent intent = new Intent();
                setResult(RESULT_OK, intent);
                finish();
                return;
            }
            adapter.setData(tally.getSkuList());
        });
        viewModel.talliedSkuLiveData.observe(this, data -> {
            barcodes.clear();
            barcodes.add(barcodeStr);
            barcodes.add(data.getSku());
            binding.tvQty.requestFocus();
            binding.tvQty.setText("1");
        });

        viewModel.errorResultCode.observe(this, code -> {
            showHint(code);
        });
        viewModel.isLoading.observe(this, b -> {
            if (b.isShow()) {
                showProgressDialog(b.getMsg());
            } else {
                dismissProgressDialog();
            }
        });

    }

    protected String setTitle() {
        return "Adjust(SKU)";
    }

    @Override
    protected int initViewModelId() {
        return BR.viewModel;
    }

    @Override
    protected void initData() {
        setNext("");
        Bundle bundle = getIntent().getBundleExtra(AppRouter.K_EXTRA);
        tally = (ReTally) bundle.getSerializable("data");
        binding.tvLpn.setText(tally.getIbLpn());

        binding.tvCode.requestFocus();
        binding.tvCode.setOnEditorActionListener(EnterListenter);

        binding.tvCode.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvQty.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                binding.tvQty.setText("");
            }
        });

        adapter = new TallyLPNAdapter(this, tally.getSkuList(), null);
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerview.setLayoutManager(layoutManager1);
        binding.recyclerview.setAdapter(adapter);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        bottomLayoutBinding.tvHint.setText("");
        initScan();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unScan();
    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_scan:
                type = 0;
                setScan();
                break;
            case R.id.iv_qty:
                String cartonsQty = binding.tvQty.getText().toString();
                if (Utils.isEmpty(cartonsQty)) {
                } else if (Integer.parseInt(cartonsQty) > 1) {
                    binding.tvQty.setText((Integer.parseInt(cartonsQty) - 1) + "");
                } else {
                    binding.tvQty.setText("0");
                }
                break;
            case R.id.tv_reset:
                binding.tvCode.setText("");
                binding.tvQty.setText("");
                break;
            case R.id.tv_next:
                if (System.currentTimeMillis() - timeMillis < spaceTime) {//两秒内触发一次
                    return;
                }
                timeMillis = System.currentTimeMillis();
                barcodeStr = binding.tvCode.getText().toString();
                if (Utils.isEmpty(barcodeStr)) {
                    ToastUtil.showToast("Scan SKU/Barcode");
                    return;
                }
                String strQty = binding.tvQty.getText().toString();
                if (Utils.isEmpty(strQty)) {
                    ToastUtil.showToast("Please scan sku to add quantity");
                    return;
                }
                int qty = Integer.parseInt(strQty);
//                if (qty == 0) {
//                    ToastUtil.showToast("Please Scan +1");
//                    return;
//                }
                AdjustLpnQr adjustLpnQr = new AdjustLpnQr();
                adjustLpnQr.setIbLpn(tally.getIbLpn());
                adjustLpnQr.setSku(barcodeStr);
                adjustLpnQr.setQty(qty);
                Bundle bundle = new Bundle();
                bundle.putSerializable("data", adjustLpnQr);
                AppRouter.showActivityForResult(mContext, AdjustSubmitActivity.class, bundle, Constant.ForResult2);
                break;
        }
    }

    private View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                type = 0;
                return;
            }

            switch (v.getId()) {
                case R.id.tv_code:
                    type = 0;
                    break;
                case R.id.tv_qty:
                    type = 1;
                    break;
            }
        }
    };


    private TextView.OnEditorActionListener EnterListenter = new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                barcodeStr = binding.tvCode.getText().toString();
                if (!Utils.isEmpty(barcodeStr)) {
                    binding.tvQty.setText("");
                    viewModel.adjustInfo(tally.getIbLpn(), barcodeStr);
                }

            }
            return false;
        }
    };

    @Override
    public void getScanninCode() {
        super.getScanninCode();

        bottomLayoutBinding.tvHint.setText("");
        switch (type) {
            case 0:
                binding.tvCode.setText(barcodeStr);
                binding.tvQty.setText("");
                viewModel.adjustInfo(tally.getIbLpn(), barcodeStr);
                break;
            case 1:
                boolean isExist = false;
                for (String str : barcodes) {
                    if (str.equalsIgnoreCase(barcodeStr)) {
                        isExist = true;
                    }
                }
                if (isExist) {
                    String ctn = binding.tvQty.getText().toString();
                    if (Utils.isEmpty(ctn)) {
                        binding.tvQty.setText(1 + "");
                    } else {
                        binding.tvQty.setText((1 + Integer.parseInt(ctn)) + "");
                    }
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.ForResult2) {
            binding.tvCode.setText("");
            binding.tvQty.setText("");
            viewModel.adjustLpn(tally.getIbLpn());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
